package me.zzp.resolver;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import me.zzp.feature.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author zhangzepeng
 */
@Slf4j
@Component
public class JsonResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private Gson gson;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(Json.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest web, WebDataBinderFactory factory) throws Exception {
        Json json = parameter.getParameterAnnotation(Json.class);
        String name = json.value().isEmpty()? parameter.getParameterName(): json.value();

        String value = web.getParameter(name);

        if (value != null && value.startsWith("{") && value.endsWith("}")) {
            try {
                return gson.fromJson(value, parameter.getParameterType());
            } catch (Throwable e) {
                log.warn("parse json({}) failed", value);
            }
        }

        return null;
    }
}
